<?php

namespace Wechat\Controller;

class OrderController extends CommonController {

    public function index() {
        $this->assign("statusEnum", C("ORDER_STATUS"));
        $this->display("index");
    }

    public function endOrder() {
        $this->assign("statusEnum", C("ORDER_STATUS"));
        $this->display("endOrder");
    }

    public function orderList() {

        $status = I("post.status");
        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;

        $map["o.customer_id"] = $this->customer["customer_id"];

        if($status == "waiting") {
            $map["o.status"] = array("in", array(
                C("ORDER_STATUS.WAITING_OPEN"),
                C("ORDER_STATUS.WAITING_CHOOSE")
            ));
        } else if($status == "end") {
            $map["o.status"] = array("in", array(
                C("ORDER_STATUS.WIN"),
                C("ORDER_STATUS.FAILURE")
            ));
        } else {
            echo json_encode(null);
            exit();
        }

        $list = D("Order")->alias("o")
            ->join("left join __ROUND__ r on r.round_id = o.round_id")
            ->join("left join __PRODUCT__ p on p.product_id = r.product_id")
            ->join("left join __GROUP__ g on g.group_id = o.group_id")
            ->join("left join __CUSTOMER__ c on c.customer_id = g.customer_id")
            ->where($map)
            ->field("c.nickname as group_name,r.round_id, r.progress, r.winner_customer_id, o.customer_id,r.pie_type,
             p.end_time,o.order_id,o.status, o.number, o.create_time, p.price, p.product_name, p.image, g.reward")
            ->order("o.order_id desc")
            ->limit(($pageNum-1)*C("DEFAULT_PAGE_SIZE"), C("DEFAULT_PAGE_SIZE"))
            ->select();

        echo json_encode($list);

    }

    public function otherOrder() {

        $bannerMap["banner_type"] = C("BANNER_TYPE.PRODUCT");
        $bannerMap["is_online"] = C("DEFAULT_YN.YES");
        $bannerList = D("Banner")
            ->where($bannerMap)->select();

        $announcementMap["is_online"] = C("DEFAULT_YN.YES");
        $announcementList = D("Announcement")
            ->where($announcementMap)
            ->order("announcement_id desc")
            ->select();

        $this->assign("announcementList", $announcementList);
        $this->assign("bannerList", $bannerList);
        $this->assign("signature",signature());
        $this->assign("appid",C('appid'));
        $this->assign("shareUrl",'http://'.$_SERVER['HTTP_HOST'].U('Order/otherOrder'));

        $this->display("otherOrder");

    }

    public function otherOrderList() {

        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;

        $map['r.status'] = C('ROUND_STATUS.WAITING');
        $map['g.status'] = C("GROUP_STATUS.WAITING_JOIN");

        $list = D('Round')->alias('r')
            ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
            ->join('LEFT JOIN __GROUP__ g ON r.round_id = g.round_id')
            ->join('LEFT JOIN __CUSTOMER__ c ON g.customer_id = c.customer_id')
            ->field('p.product_id, p.product_name, p.brief, p.image, p.price, p.end_time, c.customer_id, c.nickname,
            r.round_id, r.join_number, g.group_id, g.customer_id, g.member_number, g.buy_number')
            ->where($map)
            ->order("g.buy_number DESC")
            ->limit(($pageNum-1)*C("DEFAULT_PAGE_SIZE"), C("DEFAULT_PAGE_SIZE"))
            ->select();

        foreach($list as &$item) {
            $memberMap['gm.group_id'] = $item['group_id'];
            $item['member_list'] = D('GroupMember')->alias('gm')
                ->join('LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id')
                ->field("c.customer_id, c.headimgurl, IF(gm.customer_id = " .$item['customer_id']. ",1,0) AS is_leader")
                ->where($memberMap)
                ->order("is_leader DESC, gm.number DESC")
                ->limit(8)
                ->select();
        }

        echo json_encode($list);

    }

    public function preparePayForJoin() {

        $data["code"] = 200;

        $groupId = I("post.groupId");
        $number = intval(I("post.number"));

        if($number < 1) {
            $data["code"] = -6;
            $data["msg"] = "对不起，购买数量必须大于0";
            echo json_encode($data);
            exit();
        }

        $group = D("Group")->queryById($groupId);
        if(isNullOrEmpty($group)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，您要加入的团不存在";
            echo json_encode($data);
            exit();
        }

        if($group["status"]
            == C("GROUP_STATUS.WAITING_PAY")) {
            $data["code"] = -2;
            $data["msg"] = "对不起，您要加入的团暂时不可加入";
            echo json_encode($data);
            exit();
        }

        $round = D("Round")->queryById($group["round_id"]);

        if(isNullOrEmpty($round)) {
            $data["code"] = -3;
            $data["msg"] = "对不起，商品未开放，请及时关注";
            echo json_encode($data);
            exit();
        }

        $product = D("Product")->queryById($round["product_id"]);

        $joinNumber = D("Order")->where(array(
                "round_id" => $round["round_id"],
                "status" => array("in", array(
                    C("ORDER_STATUS.WAITING_PAY"),
                    C("ORDER_STATUS.WAITING_OPEN")
                ))
            ))->sum("number");

        $joinNumber = isNullOrEmpty($joinNumber) ? 0 : $joinNumber;

        $leftNumber = $product["price"] - $joinNumber;

        if($number > $leftNumber) {
            $data["code"] = -4;
            $data["msg"] = "有小伙伴正在准备包圆，剩余份数不足啦，请等待1分钟，如果那个小伙伴没付款，你就还有机会";
            echo json_encode($data);
            exit();
        }

        if($product["is_online"] != C("DEFAULT_YN.YES")) {
            $data["code"] = -5;
            $data["msg"] = "对不起，该商品已下架，请选择其他商品进行拼团";
            echo json_encode($data);
            exit();
        }

        $payId = D("Pay")->add(array(
            'out_trade_no' => time() . rand(0, 999),
            'money' => $number,
            'status' => 0,
            'callback' => "",
            'pay_source' => C('PAY_SOURCE.WECHAT'),
            'create_time' => getCurrentDate(),
            'update_time' => getCurrentDate()
        ));

        $orderData["round_id"] = $round["round_id"];
        $orderData["customer_id"] = $this->customer["customer_id"];
        $orderData["create_time"] = getCurrentDate();
        $orderData["update_time"] = getCurrentDate();
        $orderData["number"] = $number;
        $orderData["group_id"] = $groupId;
        $orderData["status"] = C("ORDER_STATUS.WAITING_PAY");
        $orderData["pay_id"] = $payId;

        $orderId = D("Order")->add($orderData);

        $data["order_id"] = $orderId;

        echo json_encode($data);

    }

    public function preparePay() {

        $data["code"] = 200;

        $roundId = I("post.roundId");
        $number = intval(I("post.number"));
//        $note = I("post.note");

//        if(isNullOrEmpty($note)) {
//            $data["code"] = -1;
//            $data["msg"] = "对不起，团长令不能为空";
//            echo json_encode($data);
//            exit();
//        }

        if($number < 1) {
            $data["code"] = -1;
            $data["msg"] = "对不起，购买数量必须大于0";
            echo json_encode($data);
            exit();
        }

        $round = D("Round")->queryById($roundId);

        if(isNullOrEmpty($round)) {
            $data["code"] = -2;
            $data["msg"] = "对不起，商品未开放，请及时关注";
            echo json_encode($data);
            exit();
        }

        $product = D("Product")->queryById($round["product_id"]);

        $joinNumber = D("Order")->where(array(
            "round_id" => $round["round_id"],
            "status" => array("in", array(
                C("ORDER_STATUS.WAITING_PAY"),
                C("ORDER_STATUS.WAITING_OPEN")
            ))
        ))->sum("number");

        $joinNumber = isNullOrEmpty($joinNumber) ? 0 : $joinNumber;

        $leftNumber = $product["price"] - $joinNumber;

        if($number > $leftNumber) {
            $data["code"] = -3;
            $data["msg"] = "有小伙伴正在准备包圆，剩余份数不足啦，请等待1分钟，如果那个小伙伴没付款，你就还有机会";
            echo json_encode($data);
            exit();
        }

        if($product["is_online"] != C("DEFAULT_YN.YES")) {
            $data["code"] = -4;
            $data["msg"] = "对不起，该商品已下架，请选择其他商品进行拼团";
            echo json_encode($data);
            exit();
        }

        $groupMemberMap["g.round_id"] = $round["round_id"];
        $groupMemberMap["gm.customer_id"] = $this->customer["customer_id"];
        $groupMemberMap["g.status"] = array("eq", C("GROUP_STATUS.WAITING_JOIN"));
        $groupMember = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($groupMemberMap)
            ->field("g.group_id")
            ->find();

        if(!isNullOrEmpty($groupMember)) {
            $data["code"] = -4;
            $data["msg"] = "对不起，此轮已经成为了任一团的团员，不可开团";
            echo json_encode($data);
            exit();
        }

        $groupData["round_id"] = $round["round_id"];
        $groupData["create_time"] = getCurrentDate();
        $groupData["customer_id"] = $this->customer["customer_id"];
        $groupData["status"] = C("GROUP_STATUS.WAITING_PAY");
        $groupData["reward"] = 0;
        $groupData["member_number"] = 1;
        $groupData["buy_number"] = $number;
//        $groupData["note"] = $note;

        $groupId = D("Group")->add($groupData);

        $groupMemberData["group_id"] = $groupId;
        $groupMemberData["customer_id"] = $this->customer["customer_id"];
        $groupMemberData["create_time"] = getCurrentDate();
        $groupMemberData["update_time"] = getCurrentDate();
        $groupMemberData["number"] = $number;
        $groupMemberData["reward"] = 0;

        D("GroupMember")->add($groupMemberData);

        $payId = D("Pay")->add(array(
            'out_trade_no' => time() . rand(0, 999),
            'money' => $number,
            'status' => 0,
            'callback' => "",
            'pay_source' => C('PAY_SOURCE.WECHAT'),
            'create_time' => getCurrentDate(),
            'update_time' => getCurrentDate()
        ));

        $orderData["round_id"] = $round["round_id"];
        $orderData["customer_id"] = $this->customer["customer_id"];
        $orderData["create_time"] = getCurrentDate();
        $orderData["update_time"] = getCurrentDate();
        $orderData["number"] = $number;
        $orderData["group_id"] = $groupId;
        $orderData["status"] = C("ORDER_STATUS.WAITING_PAY");
        $orderData["pay_id"] = $payId;

        $orderId = D("Order")->add($orderData);

        $data["order_id"] = $orderId;

        echo json_encode($data);

    }

    public function confirmReceive() {

        $orderId = $_REQUEST['id'];

        $order = D('Order')->alias('o')
            ->join('LEFT JOIN __GROUP__ g ON o.group_id = g.group_id')
            ->join('LEFT JOIN __ROUND__ r ON g.round_id = r.round_id')
            ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
            ->field('o.order_id, o.customer_id, o.status,
             r.round_id, p.product_id, p.product_name, p.price, p.image,
             g.group_id, g.buy_number')
            ->where(array('o.order_id' => $orderId))
            ->find();

        if($order['status'] != C('ORDER_STATUS.WAITING_CHOOSE')) {
            $this->redirect(U("Index/index"));
        }

        $round = D("Round")->queryById($order["round_id"]);
        $product = D("Product")->queryById($round["product_id"]);

        $groupMemberMap['group_id'] =$order['group_id'];
        $groupMemberMap['customer_id'] = $order['customer_id'];
        $groupMember = D('GroupMember')->where($groupMemberMap)->find();

        $priceDiff = $product['price'] - $groupMember['reward'];

        $this->assign('price', $product["price"]);
        $this->assign('order',$order);
        $this->assign('groupMember',$groupMember);
        $this->assign('priceDiff',$priceDiff);

        $this->display('confirmReceive');
    }

    public function recordListPage() {

        $id = I("get.id");

        $order = D("Order")->queryById($id);

        if(isNullOrEmpty($order)) {
            $this->redirect(U("index/index"));
        }

        $round = D("Round")->queryById($order["round_id"]);
        $product = D("Product")->queryById($round["product_id"]);

        $this->assign("order", $order);
        $this->assign("product", $product);
        $this->assign("round", $round);

        $this->display("recordListPage");

    }

    public function recordList() {

        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;
        $orderId = I("post.orderId");

        $list = D("OrderRecord")
            ->where(array("order_id"=>$orderId))
            ->limit(($pageNum-1)*60, 60)
            ->field("order_code")
            ->select();

        echo json_encode($list);

    }

    //领取现金
    public function receiveCash() {

        $data["code"] = 200;

        $orderId = I('post.orderId');

        $order = D('Order')->queryById($orderId);

        if(isNullOrEmpty($order)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，您的订单不存在";
            echo json_encode($data);
            exit();
        }

        if($order['status'] != C('ORDER_STATUS.WAITING_CHOOSE')) {
            $data["code"] = -2;
            $data["msg"] = "对不起，您的订单状态不正确";
            echo json_encode($data);
            exit();
        }

        //改变余额
        $sql = "UPDATE __CUSTOMER__ c
                LEFT JOIN __GROUP_MEMBER__ gm ON c.customer_id = gm.customer_id
                SET c.available_assets = ROUND(c.available_assets + gm.reward * ".C('DEFAULT_REWARD_FEE').",2),
                c.total_assets = ROUND(c.total_assets + gm.reward * ".C('DEFAULT_REWARD_FEE').",2)
                WHERE gm.group_id = ".$order['group_id'];

        M()->execute($sql);

        //增加流水
        $groupMemberMap['group_id'] = $order['group_id'];
        $groupMemberList = D('GroupMember')->where($groupMemberMap)->select();

        foreach ($groupMemberList as $groupMember) {
            $accountDetailData[] = array('money' => round($groupMember['reward'] * C('DEFAULT_REWARD_FEE'),2), 'customer_id' => $groupMember['customer_id'],
                'create_time' => getCurrentDate(), 'type' => C('ACCOUNT_DETAIL_TYPE.WIN'), 'refer_id' => $groupMember['group_id']);
        }

        D('AccountDetail')->addAll($accountDetailData);

        //修改订单状态
        $orderMap['group_id'] = $order['group_id'];
        $orderMap['status'] = C('ORDER_STATUS.WAITING_CHOOSE');

        $orderData['status'] = C('ORDER_STATUS.WIN');

        D('Order')->where($orderMap)->save($orderData);

        //todo 异步推送中奖团
        curlPost('http://114.215.113.76:9502/pushWechat',array('groupId' => $order['group_id']));

        echo json_encode($data);

    }

    //免费领取奖品
    public function giftForFree() {

        $data["code"] = 200;

        $orderId = I('post.orderId');

        $order = D('Order')->alias('o')
            ->join('LEFT JOIN __GROUP__ g ON o.group_id = g.group_id')
            ->join('LEFT JOIN __ROUND__ r ON g.round_id = r.round_id')
            ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
            ->field('o.*, p.product_name, p.image, p.price, g.buy_number')
            ->where(array('o.order_id' => $orderId))
            ->find();

        if(isNullOrEmpty($order)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，您的订单不存在";
            echo json_encode($data);
            exit();
        }

        if($order['status'] != C('ORDER_STATUS.WAITING_CHOOSE')) {
            $data["code"] = -2;
            $data["msg"] = "对不起，您的订单状态不正确";
            echo json_encode($data);
            exit();
        }

        $giftOrderMap['order_id'] = $orderId;
        $giftOrder = D('GiftOrder')->where($giftOrderMap)->find();

        if($giftOrder['status'] == C('DEFAULT_YN.YES')) {
            $data["code"] = -2;
            $data["msg"] = "对不起，您已完成产品购买";
            echo json_encode($data);
            exit();
        }

        $groupMemberMap['group_id'] = $order['group_id'];
        $groupMemberMap['customer_id'] = $order['customer_id'];
        $groupMember = D('GroupMember')->where($groupMemberMap)->find();

        $price = round((1 - $groupMember['number']/$order['buy_number']) * $order['price'],2);

        if($price > 0) {
            $data["code"] = -3;
            $data["msg"] = "对不起，您的订单金额不正确";
            echo json_encode($data);
            exit();
        }

        if(isNullOrEmpty($giftOrder)) {

            $giftOrderData['create_time'] = getCurrentDate();
            $giftOrderData['customer_id'] = $order['customer_id'];
            $giftOrderData['status'] = C('DEFAULT_YN.YES');
            $giftOrderData['order_id'] = $orderId;
            $giftOrderData['price'] = $price;
            $giftOrderData['address'] = I("post.address");
            $giftOrderData['mobile'] = I("post.mobile");
            $giftOrderData['name'] = I("post.name");

            $giftOrderId = D('GiftOrder')->add($giftOrderData);

            $giftOrder = D('GiftOrder')->where(array('gift_order_id' => $giftOrderId))->find();

        }

        $pay = D('Pay')->where(array('pay_id' => $giftOrder['pay_id']))->find();

        if(isNullOrEmpty($pay)) {
            $payId = D('Pay')->add(array(
                'out_trade_no' => time() . rand(0, 999),
                'money' => $giftOrder['price'],
                'status' => 1,
                'callback' => '',
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => C('PAY_SOURCE.WECHAT')
            ));

            $pay = D('Pay')->where(array("pay_id"=>$payId))->find();

            $giftOrderData['pay_id'] = $pay['pay_id'];
            D('GiftOrder')->where(array('gift_order_id' => $giftOrder['gift_order_id']))->save($giftOrderData);
        }

        //改变余额
        $sql = "UPDATE __CUSTOMER__ c
                LEFT JOIN __GROUP_MEMBER__ gm ON c.customer_id = gm.customer_id
                SET c.available_assets = ROUND(c.available_assets + gm.reward,2),
                c.total_assets = ROUND(c.total_assets + gm.reward,2)
                WHERE gm.group_id = " .$order['group_id']. "
                AND gm.customer_id != ".$order['customer_id'];

        M()->execute($sql);

        //增加流水
        $groupMemberMap['group_id'] = $order['group_id'];
        $groupMemberMap['customer_id'] = array('neq',$order['customer_id']);
        $groupMemberList = D('GroupMember')->where($groupMemberMap)->select();

        foreach ($groupMemberList as $groupMember) {
            $accountDetailData[] = array('money' => $groupMember['reward'], 'customer_id' => $groupMember['customer_id'],
                'create_time' => getCurrentDate(), 'type' => C('ACCOUNT_DETAIL_TYPE.WIN'), 'refer_id' => $groupMember['group_id']);
        }

        D('AccountDetail')->addAll($accountDetailData);

        //修改订单状态
        $orderMap['group_id'] = $order['group_id'];
        $orderMap['status'] = C('ORDER_STATUS.WAITING_CHOOSE');

        $orderData['status'] = C('ORDER_STATUS.WIN');

        D('Order')->where($orderMap)->save($orderData);

        //修改轮次状态
        $roundData['pie_type'] = C('PIE_TYPE.GIFT');
        D('Round')->where(array('round_id' => $order['round_id']))->save($roundData);

        //推送下单成功模板消息
        $messageData['openid'] = $this->customer['openid'];
        $messageData['url'] = 'http://'.$_SERVER['HTTP_HOST'].U('Product/winDetail',array('id' => $order['group_id']));
        $messageData['product_name'] = $order['product_name'];

        repeatOrderSuccess($messageData);

        //todo 异步推送中奖团
        curlPost('http://114.215.113.76:9502/pushWechat',array('groupId' => $order['group_id']));

        echo json_encode($data);

    }

    //付费领取奖品
    public function confirmOrderPrice() {

        $orderId = $_REQUEST['id'];

        $order = D('Order')->alias('o')
            ->join('LEFT JOIN __GROUP__ g ON o.group_id = g.group_id')
            ->join('LEFT JOIN __ROUND__ r ON g.round_id = r.round_id')
            ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
            ->field('o.*, p.product_name, p.image, p.price, g.buy_number')
            ->where(array('o.order_id' => $orderId))
            ->find();

        if($order['status'] != C('ORDER_STATUS.WAITING_CHOOSE')) {
            $this->redirect(U("Index/index"));
        }

        $giftOrderMap['order_id'] = $orderId;
        $giftOrder = D('GiftOrder')->where($giftOrderMap)->find();

        if($giftOrder['status'] == C('DEFAULT_YN.YES')) {
            $this->redirect(U("Index/index"));
        }

        $groupMemberMap['group_id'] = $order['group_id'];
        $groupMemberMap['customer_id'] = $order['customer_id'];
        $groupMember = D('GroupMember')->where($groupMemberMap)->find();

        if(isNullOrEmpty($giftOrder)) {

            $giftOrderData['create_time'] = getCurrentDate();
            $giftOrderData['customer_id'] = $order['customer_id'];
            $giftOrderData['status'] = C('DEFAULT_YN.NO');
            $giftOrderData['order_id'] = $orderId;
            $giftOrderData['price'] = round((1 - $groupMember['number']/$order['buy_number']) * $order['price'],2);

            $giftOrderId = D('GiftOrder')->add($giftOrderData);

            $giftOrder = D('GiftOrder')->where(array('gift_order_id' => $giftOrderId))->find();

        }

        $pay = D('Pay')->where(array('pay_id' => $giftOrder['pay_id']))->find();

        if(isNullOrEmpty($pay)) {
            $payId = D('Pay')->add(array(
                'out_trade_no' => time() . rand(0, 999),
                'money' => $giftOrder['price'],
                'status' => 0,
                'callback' => '',
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => C('PAY_SOURCE.WECHAT')
            ));

            $pay = D('Pay')->where(array("pay_id"=>$payId))->find();

            $giftOrderData['pay_id'] = $pay['pay_id'];
            D('GiftOrder')->where(array('gift_order_id' => $giftOrder['gift_order_id']))->save($giftOrderData);
        }

        //支付相关
        $arr = array(
            'appid' => C('appid'),
            'mch_id' => C('mch_id'),
            'nonce_str' => $this->createNoncestr(),
            //'sign' => '',	//签名
            'body' => '去开团商品支付',
            'out_trade_no' => $pay['out_trade_no'], //订单号
            'total_fee' => $pay['money'] * 100, //金额
//            'total_fee' => 1,
            'spbill_create_ip' => get_client_ip(),
            'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/WechatPayGift', //通知地址
            'trade_type' => 'JSAPI',
            'openid' => $this->customer['openid'],
        );

        $arr['sign'] = $this->getSign($arr);  //签名

        $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

        $arr2 = $this->xmlToArray($post);

        $jsApiObj["appId"] = C('appid');
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
        $jsApiObj["signType"] = "MD5";
        $jsApiObj["paySign"] = $this->getSign($jsApiObj);

        $this->assign('config',$this->signature());
        $this->assign('webarr',$jsApiObj);
        $this->assign('order',$order);
        $this->assign('giftOrder',$giftOrder);
        $this->assign('successUrl','http://'.$_SERVER['HTTP_HOST'].U('Order/index'));

        $this->display('confirmOrderPrice');
    }

    /**
     * 	作用：生成签名
     */
    public function getSign($Obj) {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    /**
     * 	作用：array转xml
     */
    function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml.="<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml.="<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml.="</xml>";
        return $xml;
    }

    function signature() {
        $Obj['jsapi_ticket'] = jsapi_ticket();
        $Obj['noncestr'] = createNoncestr();
        $Obj['url'] = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $Obj['timestamp'] = time();

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        //dump($Parameters);
        $String = formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        //$String = $String."&key=".C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = sha1($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        //$Obj['signature'] = strtoupper($String);
        $Obj['signature'] = $String;

        return $Obj;
    }

    /**
     * 	作用：产生随机字符串，不长于32位
     */
    public function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str.= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 	作用：将xml转为array
     */
    public function xmlToArray($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }


}